package com.wngbms.netty.seatdemo.server;

import com.wngbms.netty.seatdemo.comm.CmdType;
import com.wngbms.netty.seatdemo.message.BaseHeader;
import com.wngbms.netty.seatdemo.message.SeatOutMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

import java.nio.channels.FileChannel;

@Slf4j
public class SeatEncoderHandler extends MessageToByteEncoder<SeatOutMessage> {

    @Override
    protected void encode(ChannelHandlerContext ctx, SeatOutMessage msg, ByteBuf out) throws Exception {
        BaseHeader baseHeader = msg.getBaseHeader();
        byte[] header = baseHeader.getHeader();
        out.writeBytes(header);

        if (msg.getBody() != null && msg.getBody().length > 0) {
            out.writeBytes(msg.getBody());
        }

        if (baseHeader.getCmdType() == CmdType.BINARY_TEST_DOWNLOAD) {
            int bodyLength = baseHeader.getBodyLength();
            FileChannel fileInChannel = msg.getFileInChannel();
            int len, sentCount = 0;
//            while ((len = out.writeBytes(fileInChannel, sentCount, Math.min(out.writableBytes(), bodyLength - sentCount))) > 0) {
            while ((len = out.writeBytes(fileInChannel, sentCount, bodyLength)) > 0) {
                sentCount += len;
                log.info("正在发送文件: 本次发送:{}, 已发送:{}, 总字节数:{}", len, sentCount, bodyLength);
            }
            msg.finish();
            log.info("文件发送完成");
        }

//        log.info("encode message:{}", baseHeader.getCmdType());
    }
}
